package com.zhugang.week07;

/**
 * @program algorithms
 * @description: constructFromInPost
 * @author: chanzhugang
 * @create: 2022/07/27 17:25
 */
public class ConstructFromInPost {

    /**
     * 106 从中序和后序遍历序列构造二叉树
     *
     * @param inorder
     * @param postorder
     * @return
     */
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        return myBuildTree(postorder, 0, postorder.length - 1, inorder, 0, inorder.length - 1);
    }

    private TreeNode myBuildTree(int[] postorder, int i, int j, int[] inorder, int p, int r) {
        if (i > j) {
            return null;
        }
        // 后序遍历最后一个元素是根节点
        TreeNode root = new TreeNode(postorder[j]);
        int q = p;
        while (inorder[q] != postorder[j]) {
            q++;
        }
        int leftSize = q - p;
        TreeNode left = myBuildTree(postorder, i, i + leftSize - 1, inorder, p, q - 1);
        TreeNode right = myBuildTree(postorder, i + leftSize, j - 1, inorder, q + 1, r);
        root.left = left;
        root.right = right;
        return root;

    }


    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}